﻿jQuery.dm = {
    p: function (s) {
        return s < 10 ? '0' + s : s;
    },
    L: function (key, source) {
        if (!source) {
            source = "YdmCodeArtCore";
        }
        var result = abp.localization.localize(key, 'YdmCodeArtCore');
        return result;
    },
    getNowDate: function getNowDate() {
        var myDate = new Date();
        var year = myDate.getFullYear();
        var month = myDate.getMonth() + 1;
        var date = myDate.getDate();
        var h = myDate.getHours();
        var m = myDate.getMinutes();
        var s = myDate.getSeconds();

        var nowDate = year + '-' + this.p(month) + "-" + this.p(date) + " " + this.p(h) + ':' + this.p(m) + ":" + this.p(s);
        return nowDate;
    },
    //在Jquery里格式化Date日期时间数据
    timeStamp2String: function timeStamp2String(time) {
        var datetime = new Date();
        datetime.setTime(time);
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
        var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    },
    getQueryObj: function (url) {
        if (!url) {
            url = window.location.href;
        }
        var reg_url = /^[^\?]+\?([\w\W]+)$/,
            reg_para = /([^&=]+)=([\w\W]*?)(&|$)/g, //g is very important
            arr_url = reg_url.exec(url),
            ret = {};
        if (arr_url && arr_url[1]) {
            var str_para = arr_url[1], result;
            while ((result = reg_para.exec(str_para)) != null) {
                ret[result[1]] = result[2].replace("#", "");
            }
        }
        return ret;
    },
    getQueryString: function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]); return null;
    },
    setLangName: function (data) {
        this.setLocal("YdmCoreLangName", data);
    },
    getLangName: function () {
        return this.getLocal("YdmCoreLangName");
    },
    setAppConfig: function (option) {
        this.setLocal("AppConfigConsts", option);
    },
    getAppConfig: function () {
        return this.getLocal("AppConfigConsts");
    },
    setBuinfo: function (buInfo) {
        this.setLocal("BuInfo", buInfo);
    },
    // {id: "8f4ae5ff-e968-4629-20fb-08d73bff3f72", buName: "解放路店", storeId: "STR00000041", cwCompanyId: "UR0700000012"}
    getBuInfo: function () {
        return this.getLocal("BuInfo");
    },
    setAppInfo: function (appInfo) {
        this.setLocal("AppInfo", appInfo);
    },
    getAppInfo: function () {
        return this.getLocal("AppInfo");
    },
    setLocal: function (name, datas) {
        name = "FFF.Test." + name;
        localStorage.setItem(name, JSON.stringify(datas));
    },
    getLocal: function (name) {
        name = "FFF.Test." + name;
        return JSON.parse(localStorage.getItem(name));
    },
    deleteLocal: function (name) {
        name = "FFF.Test." + name;
        localStorage.removeItem(name);
    },
    setSession: function (name, datas) {
        name = "FFF.Test." + name;
        sessionStorage.setItem(name, JSON.stringify(datas));
    },
    getSession: function (name) {
        name = "FFF.Test." + name;
        return JSON.parse(sessionStorage.getItem(name));
    },
    deleteSession: function (name) {
        name = "FFF.Test." + name;
        sessionStorage.removeItem(name);
    },
    getCookie: function (cookieName) {
        cookieName = "FFF.Test." + cookieName;
        return $.cookie(cookieName);
    },
    getCookieObj: function (cookieName) {
        var cookie = this.getCookie(cookieName);
        if (cookie) {
            return JSON.parse(cookie);
        } else {
            return null;
        }
    },
    setCookie: function (cookieName, cookieValue, expiresDay) {
        cookieName = "FFF.Test." + cookieName;
        if (!expiresDay) {
            expiresDay = 1;
        }
        $.cookie(cookieName, cookieValue, { expires: expiresDay, path: '/' });
    },
    deleteCookie: function myfunction(cookieName) {
        cookieName = "FFF.Test." + cookieName;
        $.cookie(cookieName, '', { expires: -1, path: '/' });
    },
    setUserInfo: function (data) {
        if (data.userPwdEncry) {
            this.setCookie("sessionhtmlkey", data.userPwdEncry, 1);
        }
        delete data.userPwdEncry;

        data = JSON.stringify(data);
        this.setLocal("CurrentUserInfo", data);
    },
    // {id: "eb87bd77-d30d-40db-8d06-25d69c85e5c7", userCode: "636349", userName: "王元元", buUnitGUID: null, userImageUrl: null, …}
    getUserInfo: function () {
        return JSON.parse(this.getLocal("CurrentUserInfo"));
    },
    deleteUserInfo: function () {
        this.deleteLocal("CurrentUserInfo");
    },
    deepCopy: function (data) {
        return JSON.parse(JSON.stringify(data));
    },
    parseQueryString: function (paramData) {
        if (!(typeof paramData == "string")) {
            return paramData;
        }
        var obj = {};
        var keyvalue = [];
        var key = "",
            value = "";
        var paraString = paramData.split("&");
        for (var i = 0; i < paraString.length; i++) {
            keyvalue = paraString[i].split("=");
            key = keyvalue[0];
            value = keyvalue[1];
            if (/^\d+-\d+-\d+$/.test(value)) {
                value = value + " 00:00:00";
            }
            if (key != 'id' || (key == 'id' && value)) {
                obj[key] = decodeURIComponent(value, true).replace(/\+/g, " ");
            }
        }
        return obj;
    },
    loginOut: function () {
        location.href = "/Home/Login";
    },
    // 获取token 
    getAuthorizationCookie: function () {
        var cookie = $.cookie('Abp.AuthToken');
        // 获取token token 过期需要刷新token数据
        if (!cookie) {
            var token = '';
            var userInfo = $.dm.getUserInfo();
            var pwd = $.dm.getCookie("sessionhtmlkey")
            var data = {
                userNameOrEmailAddress: userInfo.userCode,
                password: pwd
            }
            $.ajax({
                type: "POST",
                url: "/api/services/app/TokenAuthService/Authenticate",
                data: JSON.stringify(data),
                contentType: "application/json;charset=utf-8",
                async: false,
                success: function (res) {
                    token = res.result.accessToken;
                    var seconds = res.result.expireInSeconds - 120;
                    var expire = new Date();
                    expire = expire.setTime(expire.getTime() + seconds);
                    $.cookie('Abp.AuthToken', token, { expires: expire, path: '/' });
                }
            });
            return "Bearer " + token;
        } else {
            cookie = "Bearer " + cookie;
            return cookie
        }
    },
    // 获取公司信息
    getBuHeadInfo: function () {
        var applicationInfo = $.dm.getAppInfo();
        var buInfo = $.dm.getBuInfo();
        if (applicationInfo && buInfo) {
            var storeInfo = {
                applicationGUID: applicationInfo.id,
                buGUID: buInfo.id,
                companyGUID: buInfo.companyGUID
            }
            return escape(JSON.stringify(storeInfo));
        } else {
            return null;
        }
    },

    // 传入图片的url用,分割
    showPic: function (imgUrls) {
        var imgs = imgUrls.split(",");
        var dataImg = _.map(imgs, function (item) {
            return {
                src: item
            }
        });
        layer.photos({
            photos: { data: dataImg }
        });
    },
    // 导出excel
    exportHtmlExcel: function exportHtmlExcel(id, fileName) {
        // 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
        var tableHtml = document.getElementById(id).outerHTML;
        tableHtml = tableHtml.replace(/<table/g, "<table border=1");
        var html = "<html><head><meta charset='utf-8' /></head><body>" + tableHtml + "</body></html>";
        // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
        var blob = new Blob([html], { type: "application/vnd.ms-excel", filename: '日报统计.xls' });
        var a = document.createElement('a');
        // 利用URL.createObjectURL()方法为a元素生成blob URL
        a.href = URL.createObjectURL(blob);
        // 设置文件名
        a.download = fileName + ".xls"
        a.click();
        a.remove();
    },
    // 前端导出2007格式文件  调用例子 $.dm.exportExcelDowmLoadHtmlxlsx({filename:'test',  content: document.querySelector("#tabcustloss")})
    exportExcelDowmLoadHtmlxlsx: function (data) {
        function sheet2blob(sheet, sheetName) {
            sheetName = sheetName || 'sheet1';
            var workbook = {
                SheetNames: [sheetName],
                Sheets: {}
            };
            workbook.Sheets[sheetName] = sheet; // 生成excel的配置项

            var wopts = {
                bookType: 'xlsx', // 要生成的文件类型
                bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                type: 'binary'
            };

            var wbout = XLSX.write(workbook, wopts);
            var blob = new Blob([s2ab(wbout)], {
                type: "application/octet-stream"
            }); // 字符串转ArrayBuffer
            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }
            return blob;
        }

        function openDownloadDialog(url, saveName) {
            if (typeof url == 'object' && url instanceof Blob) {
                url = URL.createObjectURL(url); // 创建blob地址
            }
            var aLink = document.createElement('a');
            aLink.href = url;
            aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
            var event;
            if (window.MouseEvent) event = new MouseEvent('click');
            else {
                event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            }
            aLink.dispatchEvent(event);
        }

        var sheet = XLSX.utils.table_to_sheet(data.content, { raw: true });// 将一个table对象转换成一个sheet对象

        openDownloadDialog(sheet2blob(sheet), data.filename + '.xlsx');

    },
    // ajax下载文件 url下载地址 不需要带domain ,data api的data数据,fileName 文件名称 例如 test.txt, success 执行成功后需要的回调函数
    // $.dm.ajaxDownFile("/api/services/app/GK11/GetQrcodeZip", data, "二维码.zip");
    ajaxDownFile: function (url, data, fileName, successCallBack) {
        var ajaxOptions = {
            type: "POST",
            url: url,
            data: JSON.stringify(data),
            xhrFields: {
                responseType: 'blob'
            },
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", $.dm.getAuthorizationCookie());
                //  request.setRequestHeader("StoreInfo", $.dm.getStoreInfo());
                request.setRequestHeader("Access-Control-Allow-Origin", "*");
                $.iMessager.progress({ 'text': '下载中...' });

            },
            processData: false,
            contentType: "application/json;charset=utf-8",
            success: function (result) {
                var excel = new Blob([result], { type: 'application/form-data' });
                var a = document.createElement("a");
                a.href = URL.createObjectURL(excel);
                a.download = fileName;
                a.click();
                a.remove();
                successCallBack && successCallBack();
                $.iMessager.progress('close');
            },
            error: function (error) {
                layer.msg("下载失败");
                $.iMessager.progress('close');
            }
        };

        $.ajax(ajaxOptions);
    },
    // ajax上传文件 ,上传的data文件, 上传成功的callback , url 没有就用框架默认的
    ajaxUploadFile: function (data, successCallBack, url) {
        var ajaxOptions = {
            type: "POST",
            url: url || $.dm.getAppConfig().PicDomain,
            data: data,
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", $.dm.getAuthorizationCookie());
                request.setRequestHeader("StoreInfo", $.dm.getStoreInfo());
            },
            processData: false,
            contentType: false,
            success: function (result) {
                if (successCallBack) {
                    var newResult = {
                        serverUrl: $.dm.getAppConfig().PicDomain + result.path,
                        url: result.path
                    }
                    successCallBack(newResult);
                }
            },
            error: function (error) {
                layer.msg("上传失败");
            }
        };
        $.ajax(ajaxOptions);
    },
    openNewTab: function (title, url, icons, functionId, number, isadd) {
        $.ei.openNewTab(title, url, icons, functionId, number, isadd)
    },
    // 打开客户详情
    openCustomerTab: function (cstId, cstName, number) {
        var url = '/CY/CY19/CY19Detail?id={0}'.format(cstId);
        $.ei.openNewTab('{0}-客户详情'.format(cstName), url, null, null, number)
    },
    // 保持页面的session
    keppSession: function () {
        var self = this;
        var timer;
        $.post("/Home/HealthyCheck", {},
            function (result) {
                timer = setTimeout(function () {
                    self.keppSession();
                }, 60000);
            }
        );
    },
    // 需要在页面先引入 <script src="~/lib/jquery.qrcode/jquery.qrcode.min.js"></script> 参考 https://blog.csdn.net/u011127019/article/details/51226104
    // 例子：$.dm.genQrcode($("#qrcode"),'12321')
    genQrcode: function (jqEle, options) {
        jqEle.qrcode(options);
    },
    // 需要在页面先引入 <script src="~/lib/jquery.qrcode/jquery.qrcode.min.js"></script> 参考 https://blog.csdn.net/u011127019/article/details/51226104
    // $.dm.genQrcode($("#qrcode"),'12321','123.png')
    downQrcode: function (jqEle, options, fileName) {
        this.genQrcode(jqEle, options);
        var canvas = jqEle.find("canvas").get(0);
        var data = canvas.toDataURL().replace("image/png", "image/octet-stream;");//获取二维码值，并修改响应头部。
        var filename = fileName || "二维码.png";//保存的图片名称和格式，canvas默认使用的png格式。这个格式效果最好。
        var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
        save_link.href = data;
        save_link.download = filename;
        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        save_link.dispatchEvent(event);
    }
}

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function (m, i) {
            return args[i];
        });
}


// 绑定快捷操作
$("html").unbind().keydown(function (e) {
    // 返回上一页
    if (e.ctrlKey && e.altKey && e.keyCode == 81) {
        if (typeof (chgPreIndexTab) != "undefined") {
            chgPreIndexTab();
        } else if (typeof (parent.chgPreIndexTab) != "undefined") {
            parent.chgPreIndexTab();
        }
        return;
    }

    // 查询菜单
    if (e.ctrlKey && e.keyCode == 81) {
        if (typeof (openSearchMenu) != "undefined") {
            openSearchMenu();
        } else if (typeof (parent.openSearchMenu) != "undefined") {
            parent.openSearchMenu();
        }
        return;
    }

    //  关闭当前页签
    if (e.ctrlKey && e.altKey && e.keyCode == 87) {
        if (typeof (closeCurrentTab) != "undefined") {
            closeCurrentTab();
        } else if (typeof (parent.closeCurrentTab) != "undefined") {
            parent.closeCurrentTab();
        }
        return;
    }
});


// 百度统计代码
var _hmt = _hmt || [];
jQuery.baiDu = {
    // 需要加入百度统计的页面
    paths: [
    ],
    initBaiDu: function () {
        (function () {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?b8a608e42d6ad8b9b79f1c117a53faaa";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
        // 控制上传的条件 https://tongji.baidu.com/web/help/article?id=324&type=0
        _hmt.push(['_requirePlugin', 'UrlChangeTracker', {
            shouldTrackUrlChange: function (newPath, oldPath) {
                return false;
            }
        }
        ]);
    },
    // 加入页面的统计
    baiduPageView: function () {
        var currentPage = window.location.pathname;
        if ($.baiDu.paths.indexOf(currentPage) != -1) {
            var pageUrl = '{0}?storeId={1}'.format(currentPage, $.dm.getBuInfo() ? $.dm.getBuInfo().storeId : '');
            _hmt.push(['_setAutoPageview', false]);
            _hmt.push(['_trackPageview', pageUrl]);
        }
    }
}

// 初始化调用
//$.baiDu.initBaiDu();
//$.baiDu.baiduPageView();